<?php
/**
 * Created by PhpStorm.
 * User: OnlyOne
 * Date: 2017/11/18
 * Time: 23:30
 */
header("Content-Type:text/html;charset=utf-8");
session_start();
//require 'user_db.php';
ini_set("display_errors", "On");
error_reporting(0);

if (!function_exists('curl_init')) {
    throw new Exception('YiBan needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
    throw new Exception('YiBan needs the JSON PHP extension.');
}
if (!function_exists('mcrypt_decrypt')) {
    throw new Exception('YiBan needs the mcrypt PHP extension.');
}

//以下三个变量内容需换成本应用的
$APPID = "a68ed95e5f19fda0";   //在open.yiban.cn管理中心的AppID
$APPSECRET = "a0d894141b4e500fff456a04dd37c6c0"; //在open.yiban.cn管理中心的AppSecret
$CALLBACK = "http://f.yiban.cn/iapp163347";  //在open.yiban.cn管理中心的oauth2.0回调地址

if(isset($_GET["code"])){   //用户授权后跳转回来会带上code参数，此处code非access_token，需调用接口转化。
    $getTokenApiUrl = "https://oauth.yiban.cn/token/info?code=".$_GET['code']."&client_id={$APPID}&client_secret={$APPSECRET}&redirect_uri={$CALLBACK}";
    $res = sendRequest($getTokenApiUrl);
    if(!$res){
        throw new Exception('Get Token Error');
    }
    $userTokenInfo = json_decode($res);
    $access_token = $userTokenInfo["access_token"];
}else{
    $postStr = pack("H*", $_GET["verify_request"]);
    if(strlen($APPID) == '16') {
        $postInfo = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $APPSECRET, $postStr, MCRYPT_MODE_CBC, $APPID);
    }else {
        $postInfo = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $APPSECRET, $postStr, MCRYPT_MODE_CBC, $APPID);
    }
    $postInfo = rtrim($postInfo);
    $postArr = json_decode($postInfo, true);
    if(!$postArr['visit_oauth']){  //说明该用户未授权需跳转至授权页面
        header("Location: https://openapi.yiban.cn/oauth/authorize?client_id={$APPID}&redirect_uri={$CALLBACK}&display=web");
        die;
    }
    $_SESSION['onethink_home']['token'] = $postArr['visit_oauth']['access_token'];
    $access_token = $postArr['visit_oauth']['access_token'];
}

//拿到access token了，接下来我们获取当前用户的基本信息试试看，so easy!
$userInfoJsonStr = sendRequest("https://openapi.yiban.cn/user/me?access_token={$access_token}");
$userInfo = json_decode($userInfoJsonStr);

function object_array($array) {
    if(is_object($array)) {
        $array = (array)$array;
    } if(is_array($array)) {
        foreach($array as $key=>$value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

$ybuser=object_array($userInfo);
$_SESSION['YiBan_usrName']=$ybuser['info']['yb_userid']."-".$ybuser['info']['yb_username'];
//echo $ybuser['info']['yb_username'];

$_SESSION['onethink_home']['userUid']=$ybuser['info']['yb_userid'];
$_SESSION['onethink_home']['userAvatar']=$ybuser['info']['yb_userhead'];
$_SESSION['onethink_home']['userSchool']=$ybuser['info']['yb_schoolname'];

header("Location:saylove.php");
//if($_SESSION['onethink_home']['username']&&$_SESSION['onethink_home']['userUid']){
//    $uid=$_SESSION['onethink_home']['userUid'];
//    $sql ="UPDATE user FROM login=login+'1' WHERE ( uid=$uid)";
//    $query=mysql_query($sql);
//    header("Location:index.php");
//}else{
//    echo 'error';
//}



function sendRequest($uri){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Yi OAuth2 v0.1');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_ENCODING, "");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $uri);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: ')); //头部要送出'Expect:
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
    //curl_setopt($ch, CURLOPT_HTTPHEADER, array());
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    $response = curl_exec($ch);
    return $response;
}

?>